package study.optional.生成optional;

import study.optional.公共类.Car;
import study.optional.公共类.Insurance;
import study.optional.公共类.User;

import java.util.Optional;
import java.util.function.Function;

/**
 * @Author 刘伟涛
 * @Date 2023/6/29 15:51
 **/
public class Demo01 {
    public static void main(String[] args) {
        User user = new User(Optional.ofNullable(new Car(Optional.ofNullable(new Insurance("上海")))));
        User user1;
        Insurance nullInsurance = null;
        Insurance insurance = new Insurance("北京");
        Optional<User> userOptional = Optional.ofNullable(user);
        Optional<Insurance> optInsurance = Optional.ofNullable(insurance);

        /*创建一个试验map的Function函数式接口方法，目的试验空值*/
        Function<Insurance,String> getName = u-> Optional.ofNullable(u)
                .map(Insurance::getName)
                .orElse("这是空的");
        String optName1 = getName.apply(insurance);
        String optName2 = getName.apply(nullInsurance);

        /*试验Optional类的flatMap方法*/
        Optional<Car> car = userOptional.flatMap(User::getCar);
        /*试验Optional类的map方法*/
        Optional<Optional<Car>> car1 = userOptional.map(User::getCar);
        /*flatMap方法与map方法的实际使用场景*/
        String name = userOptional.flatMap(User::getCar)
                .flatMap(Car::getInsurance)
                .map(Insurance::getName)
                .orElse("I don't know");
        System.out.println(name);
        System.out.println("optName1:" + optName1 + "optName2:" + optName2);
    }
}
